package org.justframework.server;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.justframework.core.Request;
import org.justframework.core.RequestHandler;
import org.justframework.core.RequestMethod;
import org.justframework.core.Response;
import org.mortbay.jetty.handler.AbstractHandler;
/**
 * handler dispatcher
 * 
 * @author whx
 */
public class HttpHandlerAdapter extends AbstractHandler {
	
	public void handle(String target, HttpServletRequest servletRequest,
			HttpServletResponse servletResponse, int dispatch) throws IOException,
			ServletException {
		Request request = new Request();
		try {
			request.setUri(new URI(target));
		} catch (URISyntaxException e) {
			e.printStackTrace();
			//404 error
			servletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
		request.setParams(servletRequest.getParameterMap());
		request.setRequestMethod(RequestMethod.valueOf(servletRequest.getMethod().toUpperCase()));
		
		Response response = null;
		RequestHandler handler = new RequestHandler();
		response = handler.handle(request, null);
		if(response != null){
			servletResponse.getWriter().write((String)response.getContent());
			servletResponse.flushBuffer();
			((org.mortbay.jetty.Request) servletRequest).setHandled(true);
			return;
		}	
		servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		return;
	}
	


}
